//
//  WDLocationManager.m
//  LocationDemo
//
//  Created by superwu_work on 16/5/25.
//  Copyright © 2016年 superwu_work. All rights reserved.
//

#import "WDLocationManager.h"
#import <CoreLocation/CoreLocation.h>
#import "AmendCoordinate.h"
void (^sucBlock)(NSDictionary *loc);
void (^errorBlock)(NSError *error);
@interface WDLocationManager ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager * locationManager;


@end

@implementation WDLocationManager

static WDLocationManager *location;
+ (WDLocationManager *)locations {
    static WDLocationManager *location = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        location = [[WDLocationManager alloc]init];
    });
    return location;
}

//定位
- (void)getCurrentLocations:(void(^)(NSDictionary *curLoc))success error:(void(^)(NSError  *error))errors
{
    
    self.locationManager = [[CLLocationManager alloc]init];
    //必须添加此判断，否则在iOS7上会crash
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
#ifdef __IPHONE_8_0
        [self.locationManager requestWhenInUseAuthorization];
#endif
    }    //定位精度(默认最好)
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if (self.distance ) {
        self.locationManager.desiredAccuracy = [self getDesiredAccuracy];
    }
    //定位更新频率(默认距离最大)
    [self.locationManager setDistanceFilter:CLLocationDistanceMax];
    if (self.distanceFilter) {
        [self.locationManager setDistanceFilter:self.distanceFilter];
    }
    

    self.locationManager.delegate = self;
    
    //成功
    sucBlock = ^(NSDictionary *locDic){
        success(locDic);
    };
    //失败
    errorBlock = ^(NSError *error){
        errors(error);
    };
    
    [self.locationManager startUpdatingLocation];//开启定位
}

- (CLLocationAccuracy)getDesiredAccuracy{
    CLLocationAccuracy distanceAccuracy;
    switch (self.distance) {
        case MLLocationAccuracyBest:
            distanceAccuracy = kCLLocationAccuracyBest;
            break;
        case MLLocationAccuracyHundredMeters:
            distanceAccuracy = kCLLocationAccuracyHundredMeters;
            break;
        case MLLocationAccuracyKilometer:
            distanceAccuracy = kCLLocationAccuracyKilometer;
            break;
        case MLLocationAccuracyThreeKilometers:
            distanceAccuracy = kCLLocationAccuracyThreeKilometers;
            break;
        case MLLocationAccuracyNearestTenMeters:
            distanceAccuracy = kCLLocationAccuracyNearestTenMeters;
            break;
        default:
            break;
    }
    return distanceAccuracy;
}


//定位
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currLocation = [[CLLocation alloc]initWithLatitude:((CLLocation *)[locations firstObject]).coordinate.latitude longitude:((CLLocation *)[locations firstObject]).coordinate.longitude];
    
    if (![AmendCoordinate isLocationOutOfChina:[currLocation coordinate]]) {
        //坐标校准(根据自己所用地图而定)
        CLLocationCoordinate2D coord_gcj = [AmendCoordinate transformFromWGSToGCJ:[currLocation coordinate]];
        CLLocationCoordinate2D coord_bd9 = [AmendCoordinate transformFromGCJToBD:coord_gcj];
        
        NSDictionary *locDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",coord_bd9.latitude], @"lat", [NSString stringWithFormat:@"%f",coord_bd9.longitude], @"long", nil];
        sucBlock(locDic);
    }else {
        NSDictionary *locDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f",currLocation.coordinate.latitude], @"lat", [NSString stringWithFormat:@"%f",currLocation.coordinate.longitude], @"long", nil];
        sucBlock(locDic);
    }
}

//关闭定位
- (void)stopUpdatingLocation{
    [self.locationManager stopUpdatingLocation];
}




#pragma mark <获取坐标位置>

//逆编码获取当前坐标信息
- (void)getCurrentAddress:(void(^)(NSMutableDictionary *citys))address error:(void(^)(NSError *error))locError{
    //通过数据源拿到当前位置
    __weak typeof(self)weak_self = self;
    [self getCurrentLocations:^(NSDictionary *curLoc) {
        [weak_self getLocAddress:[curLoc objectForKey:@"lat"] withLon:[curLoc objectForKey:@"long"] address:^(NSMutableDictionary *citys) {
            address(citys);
            [self stopUpdatingLocation];
        } error:^(NSError *error) {
            locError(error);
            [self stopUpdatingLocation];
        }];
    } error:^(NSError *error) {
        locError(error);
    }];
}

//逆编码获取坐标信息
- (void)getLocAddress:(NSString *)lat withLon:(NSString *)lon address:(void(^)(NSMutableDictionary *citys))address error:(void(^)(NSError *error))getFail{
    //使用地理位置 逆向编码拿到位置信息
    if (lat != nil && lon != nil) {
        CLGeocoder * geocoder = [[CLGeocoder alloc]init];
        CLLocation * currentLoc = [[CLLocation alloc]initWithLatitude:[lat floatValue] longitude:[lon floatValue]];
        [geocoder reverseGeocodeLocation:currentLoc completionHandler:^(NSArray *placemarks, NSError *error) {
            //逆编码完毕以后调用此block
            if (!error) {
                CLPlacemark * placeMark = placemarks[0];
                NSMutableDictionary *locDicationary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:lat,@"lat", lon, @"long",placeMark.country,@"country", [placeMark.addressDictionary objectForKey:@"State"],@"State",placeMark.locality,@"city",placeMark.subLocality,@"subLocality",placeMark.thoroughfare,@"thoroughfare",placeMark.name,@"street",nil];
                address(locDicationary);
                //获取当前地址城市名
            }else{
                NSLog(@"逆编码失败");
            }}];
    }
}




@end
